import { Collection, MongoClient, MongoClientOptions } from 'mongodb'
import { BaseInfo, ChatRoom, LogMessage, UploadInfo } from './interfaces'
import config from './config'

export interface Collections {
    'chatroom': ChatRoom & BaseInfo;
    'log': LogMessage & BaseInfo;
    'upload': UploadInfo & BaseInfo;
}
export type CollectionsKey = keyof Collections

export class DBCenter {
    private __client: MongoClient
    private dbName: string
    constructor(uri: string, dbName: string, config: MongoClientOptions) {
        this.__client = new MongoClient(uri, config)
        this.dbName = dbName
    }
    async getCollection <T extends CollectionsKey> (doc: T): Promise<Collection<Collections[T]>> {
        const { __client, dbName } = this
        await __client.connect()
        return __client.db(dbName).collection(doc)
    }
}

export default new DBCenter(config.mongodb.uri, config.mongodb.dbName, config.mongodb.config)
